package com.youjiang.meeting.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.youjiang.meeting.mapper.WxconfigMapper;
import com.youjiang.meeting.po.UserInfo;
import com.youjiang.meeting.po.Wxconfig;
import com.youjiang.meeting.po.WxconfigExample;
import com.youjiang.meeting.service.WeiXinMassegeService;
import com.youjiang.meeting.service.impl.WeiXinMassegeServiceImpl;
import com.youjiang.meeting.utils.StringKeyValue;
import com.youjiang.meeting.utils.ToolUtils;
import com.youjiang.meeting.utils.weixin.CheckUtil;
import com.youjiang.meeting.utils.weixin.MessageUtil;
import com.youjiang.meeting.utils.weixin.Sign;
import com.youjiang.meeting.utils.weixin.WeixinUtil;

/**
 * <p>
 * Title: WeixinController
 * </p>
 * <p>
 * Description:微信对接
 * </p>
 */
@Controller
@Scope("prototype")
public class WeixinController {
	@Resource
	private WeiXinMassegeService service;
	@Autowired
	private WxconfigMapper wMapper;
	
	
	/***
	 * 微信授权回调地址
	 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx93674986ccf2a09b&redirect_uri=http://feng.tunnel.qydev.com/authorization.action&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
	 * 
	 * @param code
	 * @param state
	 * @param req
	 * @return
	 */
	
	@RequestMapping(value="/authorization",produces=StringKeyValue.CONTROLLERPRODUCES)
	public ModelAndView authorizationInfo(String code,String state,HttpServletRequest req){
		
		ModelAndView model = service.authorization(code, state, true, req);
		return model;
	}
	
	@RequestMapping(value="/redpage",produces=StringKeyValue.CONTROLLERPRODUCES)
	@ResponseBody
	public String redPackge(String code,String state,HttpServletRequest req){
		service.authorization(code, state, false, req);
		return "红包页面";
	}
	@RequestMapping(value="/weixin",method={RequestMethod.POST,RequestMethod.GET},produces=StringKeyValue.CONTROLLERPRODUCES)
	@ResponseBody
	public String weixin(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
		String modth = request.getMethod();
		String data="";
		if (modth.equalsIgnoreCase("get")) {
			data = doGet(request, response);
		} else {
		    data = doPost(request, response);
		}
		return data;
	}

	// get方法的检验
	private String doGet(HttpServletRequest req, HttpServletResponse resp) {
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			System.out.println("------"+echostr);
			return echostr;
		}
		System.out.println("--------"+echostr);
		return null;
	}

	// post消息的接收与回复
	private String doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		
		// 接收参数微信加密签名、 时间戳、随机数
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		if (CheckUtil.checkSignature(signature, timestamp, nonce)){
			Map<String, String> map = MessageUtil.XMLToMessage(request);
			String data = service.receive(map);
			return data;
		}
		return null;

	}

	public String sign(String nowurl,HttpServletRequest req,String appid,String appsecrect) throws Exception {
		if (StringUtils.isEmpty(WeixinUtil.SYSTEMPATH)) {
			WeixinUtil.SYSTEMPATH=req.getServletContext().getRealPath("/weixinfile/");
		}
		Map<String, String> info = Sign.sign(nowurl,appid,appsecrect);
		Gson gson = new Gson();
		return gson.toJson(info);
	}
}
